package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Classname LoginController
 * @Description TODO
 * @Date 2021/9/18 14:49
 * @Author Anonymous
 */
@SuppressWarnings("all")
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo") // 得到redis中的存储过的user信息，返回给子系统的session中
    public Object userInfo(@RequestParam("token") String token){
        // 拿着其他域名转发过来的token去redis里查
        Object loginUser = redisTemplate.opsForValue().get(token);
        return loginUser;
    }

    @RequestMapping("/doLogin")
    public String doLogin(String username,
                          String password,
                          String url,
                          HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {//简单认为登录正确
            //把登录成功的用户存起来，用session或者redis都可以
            String redisKey = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(redisKey, username);

            // 存储cookie， 是在server.com域名下存
            Cookie cookie = new Cookie("sso_token", redisKey);
            response.addCookie(cookie);
            return "redirect:" + url + "?token=" + redisKey;//登录成功，跳回之前页面
        }
        //登录失败，展示登录页
        return "login";
    }

    @RequestMapping("/login.html") // 子系统都来这
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {//这里继续和redis中的值比较一下更安全
            //说明子系统已经登录过
            return "redirect:" + url + "?token=" + sso_token;//登录成功，跳回之前页面
        }
        model.addAttribute("url", url);
        System.out.println(url + "========================");
        // 子系统都没登录过才去登录页
        return "login";
    }
}
